<!--
 * @FilePath: /fxfzywpt/src/views/uncertain/testProvince.vue
 * @Description: 
-->
<template>
  <div style="width: 100%; height: 100%; position: relative">
    <button @click="click">添加</button>
    <div id="map"></div>
  </div>
</template>

<script>
import { getSqlTempLayer } from '@/utils/sqlTempLayersSet';
import { getTileLayerByName } from '@/utils/matchProvince';
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import XYZ from 'ol/source/XYZ';
import * as olProj from 'ol/proj';
import Draw from 'ol/interaction/Draw';
import Overlay from 'ol/Overlay';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';
import { OSM, Vector as VectorSource } from 'ol/source';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import Feature from 'ol/Feature';
import { Point, MultiLineString, LineString, Polygon } from 'ol/geom';
import { fromLonLat } from 'ol/proj';
import Circle from 'ol/geom/Circle';
import { ScaleLine, defaults as defaultControls } from 'ol/control';
import { circular } from 'ol/geom/Polygon';
import * as olSphere from 'ol/sphere';
import LinearRing from 'ol/geom/LinearRing';
import { getTransform } from 'ol/proj';
import { getArea, getLength, getDistance } from 'ol/sphere';
import { unByKey } from 'ol/Observable';
import WMTS from 'ol/source/WMTS';
import ImageLayer from 'ol/layer/Image';
import ImageWMS from 'ol/source/ImageWMS';
import TileWMS from 'ol/source/TileWMS';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import * as olExtent from 'ol/extent';
import GeoJSON from 'ol/format/GeoJSON';
import Text from 'ol/style/Text';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import {
  getChinaBaseLayer,
  getChinaBaseProvinceLayer,
  getTiandituImgMap,
  getTiandituDemMap,
  getBeiJingLayer,
  getChinaBaseLayer3857,
  getTileLayer,
  getBaseDir,
  getGridLayer,
} from '@/map/projMap.js';
import { ArcgisService } from '@/map/ArcgisService';
import {
  GetGridCellInfosParameters,
  GridCellInfosService,
  MapService,
  GetFeaturesByGeometryParameters,
  FeatureService,
  Util,
  TileSuperMapRest,
  QueryBySQLParameters,
  QueryService,
} from '@supermap/iclient-ol';

var map = null; // /地图实例
var view = null; // 视图实例

export default {
  name: 'Home',
  components: {},
  data() {
    return {
      features: null,
      layers: null,
    };
  },

  mounted() {
    this.initMap();
    // let layer = getSqlTempLayer('/services/map-datacenter/rest/maps/jc_ds_gpb_gdzc_grid_total_housing@datacenter');
    let url = '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_keynote_target_data@fxfzfxqh';
    let name = '学校';
    let sqlText = `type='${name}'`;
    getSqlTempLayer(url, sqlText).then((layer) => {
      console.log('layer---', layer);
      map.addLayer(layer);
    });
  },

  methods: {
    // 初始化地图
    async initMap() {
      // 实例化Map
      map = new Map({
        target: 'map',
        view: new View({
          // center: [11523496.18, 3735091.51],
          // zoom: 4,
          // multiWorld: true,
          center: [116.403218, 39.92372],
          zoom: 4,
          constrainResolution: true, // 设置缩放级别为整数
          smoothResolutionConstraint: false, // 关闭无级缩放地图
          projection: 'EPSG:4490',
        }),
      });

      view = map.getView();
      map.on('click', (event) => {
        const clickedFeature = map.forEachFeatureAtPixel(event.pixel, (feature) => feature);
        console.log(clickedFeature);
        return;
        if (clickedFeature) {
          // 获取点击的省份边界
          const provinceGeometry = clickedFeature.getGeometry();

          // 移除或隐藏其他省份图层
          map.getLayers().forEach((layer) => {
            // if (layer !== provinceLayer.value) {
            if (layer.get('id') !== 'province') {
              // mapInstance.value.removeLayer(layer);
              layer.setVisible(false);
            } else {
              layer.setVisible(true);
              // layer
              //   .getSource()
              //   .getFeatures()
              //   .forEach((feature) => {
              //     console.log('-----', clickedFeature.get('name'), feature.get('name'));
              //     if (clickedFeature.get('name') !== feature.get('name')) {
              //       feature.setStyle(null);
              //     }
              //   });
            }
          });
          // 创建新的省份图层并添加到地图
          // const newProvinceLayer = new VectorLayer({
          //   source: new VectorSource({
          //     features: [new Feature(provinceGeometry)],
          //   }),
          //   zIndex: 2,
          //   style: new Style({
          //     stroke: new Stroke({
          //       color: 'blue',
          //       width: 2,
          //     }),
          //     fill: new Fill({
          //       color: 'black',
          //     }),
          //   }),
          // });
          // map.addLayer(newProvinceLayer);
          // 计算放大后的视图范围
          const provinceExtent = provinceGeometry.getExtent();
          // 更新地图视图以显示具体的省份地图
          map.getView().fit(provinceExtent, { padding: [20, 20, 20, 20], duration: 1000 }); // 1000毫秒的动画效果
        }
      });
      // 加载圆形
      // this.addPoint();
      // this.addChinaBlue(map);
      // this.createProvinceLayer();
      // this.addLineLayer();
      // let layer = await getTileLayerByName('北京市', map);
      // layer.setZIndex(1);
      // map.addLayer(layer);
    },
    // 请求底图
    addChinaBlue(map) {
      getChinaBaseLayer(map);
      // let arc = new ArcgisService({ map });
      // arc.getSqlFilterLayer('dd');
      let arcgisService = new ArcgisService({ map });
      let aa = arcgisService.showArcgisHddcLayer('全新世断层');
      aa.then((data) => {
        let layer = data.get('全新世断层');
        map.addLayer(layer);
        Util.setMask(layer, this.features[0]);
      });
      let bb = arcgisService.showArcgisHddcLayer('晚更新世断层');
      bb.then((data) => {
        let layer = data.get('晚更新世断层');
        map.addLayer(layer);
        Util.setMask(layer, this.features[0]);
      });
      // let cc = arcgisService.showArcgisHddcLayer('早中更新世断层');
      // cc.then((data) => {
      //   let layer = data.get('早中更新世断层');
      //   map.addLayer(layer);
      //   Util.setMask(layer, this.features[0]);
      // });
      // let dd = arcgisService.showArcgisHddcLayer('前第四纪断层');
      // dd.then((data) => {
      //   let layer = data.get('前第四纪断层');
      //   map.addLayer(layer);
      //   Util.setMask(layer, this.features[0]);
      // });
      // getChinaBaseProvinceLayer(map);
      // getTileLayer('/iserver/services/map-shpypg/rest/maps/历史设定地震点数据', map);
      // getChinaBaseLayer3857(map);
      //   getBeiJingLayer(map);
    },
    createProvinceLayer() {
      // let baseurl = 'https://iserver.supermap.io/iserver/services/map-china400/rest/maps/China';
      // var layer = new TileLayer({
      //   source: new TileSuperMapRest({
      //     url: baseurl,
      //     wrapX: true,
      //   }),
      // });
      // map.addLayer(layer);
      // const geojsonSource = new VectorSource({
      //   url: getBaseDir('China_4490.json'), // 替换为你的 GeoJSON 数据源路径
      //   format: new GeoJSonFormat(),
      // });

      // let provinceLayer = new VectorLayer({
      //   source: geojsonSource,
      //   zIndex: 1,
      //   id: 'province',
      // });
      // map.addLayer(provinceLayer);
      // 使用 fetch 方法获取 GeoJSON 数据
      fetch(getBaseDir('China_4490.json'))
        .then((response) => response.json()) // 将响应解析为 JSON 数据
        .then((geojson) => {
          // 使用 GeoJSON 格式解析器将数据转换为 Features
          const geojsonFormat = new GeoJSON();
          this.features = geojsonFormat.readFeatures(geojson);
          console.log('--feature', this.features[0]);

          // // 将解析后的 Features 添加到 VectorLayer
          // vectorLayer.getSource().addFeatures(features);
        })
        .catch((error) => {
          console.error('Error fetching or processing GeoJSON:', error);
        });
    },
    addLineLayer() {
      let url = '/iserver/services/map-shpypg/rest/maps/五代图全国断裂';
      getGridLayer(url).then((layer) => {
        map.addLayer(layer);
        this.layers = layer;
        console.log('this...', this.layers);
      });
    },
    click() {
      // let that = this;
      // let baseUrl = 'https://iserver.supermap.io/iserver/services/map-china400/rest/maps/China';
      // var param = new QueryBySQLParameters({
      //   queryParams: {
      //     name: 'China_Province_pl@China',
      //     attributeFilter: 'SMID =14',
      //   },
      // });
      // new QueryService(baseUrl).queryBySQL(param, function (serviceResult) {
      //   console.log(serviceResult.result);
      //   // widgets.loader.removeLoader();
      //   let sichuanFeature = new GeoJSON().readFeatures(serviceResult.result.recordsets[0].features)[0];
      //   console.log('sichuanFeature---', sichuanFeature);
      //   Util.setMask(that.layers, sichuanFeature);
      // });
      console.log('first----', this.features[0]);
      // todo
      Util.setMask(this.layers, this.features[0]);
      // Util.setMask(this.layers, this.features[1]);
      // Util.setMask(this.layers, this.features[2]);
      // Util.setMask(this.layers, this.features[3]);
      // Util.setMask(this.layers, this.features[4]);
    },
    // 绘制圆
    addPoint() {
      let sites = [
        {
          site: [116.400819, 39.916263],
          name: '覆盖物1',
        },
        {
          site: [116.450819, 39.917263],
          name: '覆盖物2',
        },
        {
          site: [116.350819, 39.857263],
          name: '覆盖物3',
        },
      ];
      let features = [];
      sites.forEach((item, index) => {
        let feature = new Feature({
          title: item.name,
          geometry: new Circle(fromLonLat(item.site), this.getRadius(2000)),
        });
        feature.setStyle(
          new Style({
            fill: new Fill({
              color: 'rgba(32, 157, 230, 1)',
            }),
          })
        );
        features.push(feature);
      });
      let source = new VectorSource();
      source.addFeatures(features);
      let layer = new VectorLayer({
        opacity: 0.2,
      });
      layer.setSource(source);
      map.addLayer(layer);
      this.addLabel();
      this.addLink();
    },

    // 添加标识
    addLabel() {
      let sites = [
        {
          site: [116.400819, 39.916263],
          name: '覆盖物1',
        },
        {
          site: [116.450819, 39.917263],
          name: '覆盖物2',
        },
        {
          site: [116.350819, 39.857263],
          name: '覆盖物3',
        },
      ];
      let features = [];
      sites.forEach((item, index) => {
        let feature = new Feature({
          title: item.name,
          geometry: new Point(fromLonLat(item.site)),
        });
        feature.setStyle(
          new Style({
            text: new Text({
              textAlign: 'center', //位置
              textBaseline: 'middle', //基准线
              font: 'normal 17px 微软雅黑', //文字样式
              text: item.name, //文本内容
              fill: new Fill({
                //文本填充样式（即文字颜色)
                color: 'red',
              }),
            }),
          })
        );
        features.push(feature);
      });

      let sourceLabel = new VectorSource();
      sourceLabel.addFeatures(features);
      let layerLabel = new VectorLayer({
        opacity: 1,
      });
      layerLabel.setSource(sourceLabel);
      map.addLayer(layerLabel);
    },

    // 添加连线
    addLink() {
      let sites = [
        {
          site: [116.400819, 39.916263],
          name: '覆盖物1',
        },
        {
          site: [116.450819, 39.917263],
          name: '覆盖物2',
        },
        {
          site: [116.350819, 39.857263],
          name: '覆盖物3',
        },
      ];
      sites.push(sites[0]);
      let linkData = [];
      sites.forEach((item) => {
        linkData.push(fromLonLat(item.site));
      });
      let features = [];

      let featureLine = new Feature({
        geometry: new LineString(linkData),
      });
      let lineStyle = new Style({
        stroke: new Stroke({
          color: '#000',
          lineDash: [10, 10, 10, 10], // 重点在这
          width: 2,
        }),
      });
      // 添加线的样式
      featureLine.setStyle(lineStyle);
      features.push(featureLine);

      let distanceList = [];
      for (let index = 0; index < sites.length - 1; index++) {
        let site = fromLonLat([
          (sites[index].site[0] + sites[index + 1].site[0]) / 2,
          (sites[index].site[1] + sites[index + 1].site[1]) / 2,
        ]);
        let length = getDistance(sites[index].site, sites[index + 1].site);
        distanceList.push({
          site,
          length,
        });
      }

      distanceList.forEach((item) => {
        let feature = new Feature({
          title: '这是测试用的',
          geometry: new Point(item.site),
        });
        feature.setStyle(
          new Style({
            text: new Text({
              textAlign: 'center', //位置
              textBaseline: 'middle', //基准线
              font: 'normal 12px 微软雅黑', //文字样式
              text: item.length.toFixed(0) + 'm', //文本内容
              padding: [1, 1, 1, 1],
              backgroundFill: new Fill({
                //文本填充样式（即文字颜色)
                color: '#d5e2f9',
              }),
              fill: new Fill({
                //文本填充样式（即文字颜色)
                color: 'red',
              }),
            }),
          })
        );
        features.push(feature);
      });

      let sourceLink = new VectorSource();
      sourceLink.addFeatures(features);
      let layerLink = new VectorLayer();
      layerLink.setSource(sourceLink);
      map.addLayer(layerLink);
    },

    // 半径计算
    getRadius(radius) {
      let metersPerUnit = map.getView().getProjection().getMetersPerUnit();
      let circleRadius = radius / metersPerUnit;
      return circleRadius;
    },
  },
};
</script>
<style scoped>
#map {
  width: 100%;
  height: 100%;
  background-color: azure;
}
</style>

<style scoped>
/* /deep/.ol-tooltip {
  position: relative;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 4px;
  color: white;
  padding: 4px 8px;
  opacity: 0.7;
  white-space: nowrap;
  font-size: 12px;
  cursor: default;
  user-select: none;
}

/deep/.ol-tooltip-measure {
  opacity: 1;
  font-weight: bold;
}

/deep/.ol-tooltip-static {
  background-color: #ffcc33;
  color: black;
  border: 1px solid white;
}

/deep/.ol-tooltip-measure:before,
/deep/.ol-tooltip-static:before {
  border-top: 6px solid rgba(0, 0, 0, 0.5);
  border-right: 6px solid transparent;
  border-left: 6px solid transparent;
  content: '';
  position: absolute;
  bottom: -6px;
  margin-left: -7px;
  left: 50%;
}

:deep(.ol-tooltip-static:before) {
  border-top-color: #ffcc33;
} */
</style>
